/////*system header*//////
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
/////*user header*/////
#include "../include/test.h"
#include "../include/hello.h"

/////*global variables */////
// Command mapping table
Command commands[] = {
    /*function from ../sources/hello.c*/
    {"hello",  hello, "","",NULL},
    {NULL,        NULL,                     NULL,                                     NULL,                                       NULL}
};

/////*functions */////
int main(int argc,char *argv[])
{
    // No arguments, show general help
    if (argc < 2) 
    {
        print_general_help(argv[0]);
        return 1;
    }

    // Find command
    Command *cmd = find_command(argv[1]);
    if (!cmd) 
    {
        printf("Error: Unknown command '%s'\n", argv[1]);
        print_general_help(argv[0]);
        return 1;
    }

    // Extract subcommand arguments (starting from argv[2])
    int sub_argc = argc - 1;
    char **sub_argv = &argv[1];

    // Parameter validation
    if (cmd->validator && cmd->validator(sub_argc) != 0) 
    {
        printf("Error: Invalid parameter format\n");
        print_command_help(cmd->name,argv[0]);
        return 1;
    }

    // Execute command handler function
    cmd->handler(sub_argc, sub_argv);

    return 0;
}

// Find command handler function
Command* find_command(const char *name) 
{
    for (int i = 0; commands[i].name != NULL; i++) 
    {
        if (strcmp(commands[i].name, name) == 0) 
        {
            return &commands[i];
        }
    }
    return NULL;
}

// Get program name
const char* get_progname(void) {
    static char *progname = NULL;
    if (!progname) {
        progname = strrchr(__FILE__, '/');
        progname = progname ? progname + 1 : __FILE__;
    }
    return progname;
}

// Display general help information
void print_general_help(char *str) {
    printf("Usage: %s [command] [arguments...]\n", str);
    printf("Available commands:\n");
    for (int i = 0; commands[i].name != NULL; i++) {
        printf("  %-10s - %s\n", commands[i].name, \
            commands[i].description);
    }
    //printf("\nUse '%s help [command]' for detailed information about a specific command\n", 
    //    argv[0]);
}

// Display specific command help information
void print_command_help(const char *cmd_name,char *str) {
    Command *cmd = find_command(cmd_name);
    if (cmd) {
        printf("Command: %s - %s\n", cmd->name, cmd->description);
        if (cmd->usage[0]) {
            printf("Usage: %s %s %s\n", str, \
            cmd->name, cmd->usage);
        }
    } else {
        printf("Error: Unknown command '%s'\n", cmd_name);
        print_general_help(str);
    }
}

// Help command handler function
void print_help(int argc, char *argv[]) {
    if (argc > 1) {
        print_command_help(argv[1],argv[0]);
    } else {
        print_general_help(argv[0]);
    }
}
